#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->splitter_13->setStretchFactor(1, 3);
    TcpInit();
    initChart();
    size_temp = 0;
    size_humi = 0;
    size_Light = 0;
    size_Water = 0;
    size_Weight = 0;
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::TcpInit()
{
    tcpSocket=new QTcpSocket(this);
    connect(tcpSocket,&QTcpSocket::readyRead,
            this,&MainWindow::onReadMessage);
    connect(tcpSocket,SIGNAL(QAbstractSocket::SocketError),
            this,SLOT(onDisplayError(QAbstractSocket::SocketError)));

}

void MainWindow::onReadMessage()
{
    QByteArray bt;
    bt.resize(tcpSocket->bytesAvailable());
    tcpSocket->read(bt.data(),bt.size());
    //将客户端反馈的数据显示到标签上
    //ui->textBrowser->setText(bt);

    ShowData(bt);

}

void MainWindow::ShowData(QByteArray bt)
{
    QList<QByteArray>list = bt.split('&');
    if(list.size()<3)
        return;
    QList<QByteArray>list1 = list[2].split('=');

    QList<QByteArray>list2 = list[3].split('=');

    if(list1[1] == "temp")
    {
        if(list2[1].length()>4)
        {
            QList<QByteArray>list3 = list2[1].split('\r');
            ui->lineEdit_temp->setText(list3[0]);
            Point_temp(list3[0].toDouble());
        }
        else {
            ui->lineEdit_temp->setText(list2[1]);
            Point_temp(list2[1].toDouble());
        }

    }

    if(list1[1] == "humi")
    {
        if(list2[1].length()>4)
        {
            QList<QByteArray>list3 = list2[1].split('\r');
            ui->lineEdit_humi->setText(list3[0]);
            Point_humi(list3[0].toDouble());
        }
        else {
            ui->lineEdit_temp->setText(list2[1]);
            Point_humi(list2[1].toDouble());
        }
    }
    if(list1[1] == "Open1")
    {
        if(list2[1] == "1\r\r\n")
        {
            ui->pushButton_2->setText("开启状态");
        }
        else if(list2[1] == "0\r\r\n")
        {
            ui->pushButton_2->setText("关闭状态");
        }
    }

    if(list1[1] == "Open2")
    {
        if(list2[1] == "1\r\r\n")
        {
            ui->pushButton_3->setText("开启状态");
        }
        else if(list2[1] == "0\r\r\n")
        {
            ui->pushButton_3->setText("关闭状态");
        }
    }
    if(list1[1] == "Light")
    {
        if(list2[1].length()>4)
        {
            QList<QByteArray>list3 = list2[1].split('\r');
            ui->lineEdit_Light->setText(list3[0]);
            Point_Light(list3[0].toDouble());
        }
        else {
            ui->lineEdit_Light->setText(list2[1]);
            Point_Light(list2[1].toDouble());
        }
    }
    if(list1[1] == "weight")
    {
        if(list2[1].length()>4)
        {
            QList<QByteArray>list3 = list2[1].split('\r');
            ui->lineEdit_Weight->setText(list3[0]);
            Point_Weight(list3[0].toDouble());
        }
        else {
            ui->lineEdit_Weight->setText(list2[1]);
            Point_Weight(list2[1].toDouble());
        }
    }
    if(list1[1] == "water")
    {
        if(list2[1].length()>4)
        {
            QList<QByteArray>list3 = list2[1].split('\r');
            ui->lineEdit_water->setText(list3[0]);
            Point_Water(list3[0].toDouble());
        }
        else {
            ui->lineEdit_water->setText(list2[1]);
            Point_Water(list2[1].toDouble());
        }
    }
    if(list1[1] == "AutoSet")
    {
        if(list2[1] == "1\r\r\n")
        {
            ui->pushButton_4->setText("自动控制");
        }
        else if(list2[1] == "0\r\r\n")
        {
            ui->pushButton_4->setText("手动控制");
        }
    }
}

void MainWindow::onDisplayError(QAbstractSocket::SocketError e)
{
    qDebug()<<"SocketError:"<<e<<endl
           <<tcpSocket->errorString();

}

void MainWindow::on_pushButton_clicked()
{
    if(!isconnect)
    {
        try {
            tcpSocket->abort();
            //连接服务端
            if(ui->lineEdit->text().isEmpty())
            {
                ui->textEdit->setText("密钥为空，请检查");
                goto aa;
            }
            else {
                pass = ui->lineEdit->text();
            }
            tcpSocket->connectToHost("bemfa.com",8344);
            QString str = "cmd=1&uid=" + pass + "&topic=temp\r\n";
            tcpSocket->write(str.toUtf8());
            str = "cmd=1&uid=" + pass + "&topic=humi\r\n";
            tcpSocket->write(str.toUtf8());
            str = "cmd=1&uid=" + pass + "&topic=Open1\r\n";
            tcpSocket->write(str.toUtf8());
            str = "cmd=1&uid=" + pass + "&topic=Open2\r\n";
            tcpSocket->write(str.toUtf8());
            str = "cmd=1&uid=" + pass + "&topic=Light\r\n";
            tcpSocket->write(str.toUtf8());
            str = "cmd=1&uid=" + pass + "&topic=weight\r\n";
            tcpSocket->write(str.toUtf8());
            str = "cmd=1&uid=" + pass + "&topic=water\r\n";
            tcpSocket->write(str.toUtf8());
            str = "cmd=1&uid=" + pass + "&topic=AutoSet\r\n";
            tcpSocket->write(str.toUtf8());
            ui->pushButton->setText("断开连接");
            isconnect = true;
        } catch(...)
        {
            isconnect = false;
        }
        aa:
            ;
    }
    else
    {
        tcpSocket->abort();
        ui->pushButton->setText("连接云端");
        isconnect = false;
    }
}


void MainWindow::initChart()            //初始化的实时检测
{
    ui->widget->axisRect()->setBackground(QBrush(Qt::black));

    ui->widget->legend->setVisible(true);
    ui->widget->xAxis->setLabel("Time(s)");//设置ｘ轴
    ui->widget->xAxis->setTicks(true);

    ui->widget->yAxis->setLabel("%/℃");//设置ｙ轴
    ui->widget->yAxis->setTicks(true);


    graph1 = ui->widget->addGraph();//增加一条光照曲线图层
    graph2 = ui->widget->addGraph();//增加一条温度曲线图层
    graph3 = ui->widget->addGraph();//增加一条湿度曲线图层
    graph4 = ui->widget->addGraph();//增加一条重量曲线图层
    graph5 = ui->widget->addGraph();//增加一条水位曲线图层

    QCPScatterStyle QCPcs1(QCPScatterStyle::ssSquare, QColor(255,0,0),QColor(255,0,0),3);//设置折线图的点的形状及颜色
    QPen qPen1(QColor(255,0,0));
    graph1->setScatterStyle(QCPcs1);
    graph1->setPen(qPen1);//设置画笔颜色
    graph1->setName(QString("光照"));


    QCPScatterStyle QCPcs4(QCPScatterStyle::ssCircle, QColor(0,255,0),QColor(0,255,0),3);//设置折线图的点的形状及颜色
    QPen qPen4(QColor(0,255,255));
    graph4->setScatterStyle(QCPcs4);
    graph4->setPen(qPen4);//设置画笔颜色
    graph4->setName(QString("重量"));

    QCPScatterStyle QCPcs5(QCPScatterStyle::ssSquare, QColor(0,0,255),QColor(0,0,255),3);//设置折线图的点的形状及颜色
    QPen qPen5(QColor(255,255,0));
    graph5->setScatterStyle(QCPcs5);
    graph5->setPen(qPen5);//设置画笔颜色
    graph5->setName(QString("水位"));

    QCPScatterStyle QCPcs2(QCPScatterStyle::ssCircle, QColor(0,255,255),QColor(0,255,255),3);//设置折线图的点的形状及颜色
    QPen qPen2(QColor(0,255,0));
    graph2->setScatterStyle(QCPcs2);
    graph2->setPen(qPen2);//设置画笔颜色
    graph2->setName(QString("温度"));

    QCPScatterStyle QCPcs3(QCPScatterStyle::ssCircle, QColor(255,255,0),QColor(255,255,0),3);//设置折线图的点的形状及颜色
    QPen qPen3(QColor(0,0,255));
    graph3->setScatterStyle(QCPcs3);
    graph3->setPen(qPen3);//设置画笔颜色
    graph3->setName(QString("湿度"));

    ui->widget->xAxis->ticker()->setTickCount(11);//11个主刻度
    ui->widget->xAxis->ticker()->setTickStepStrategy(QCPAxisTicker::tssReadability);
    ui->widget->yAxis->ticker()->setTickCount(11);

    ui->widget->yAxis->setRangeLower(0);
    ui->widget->xAxis->setRangeLower(0);
    ui->widget->xAxis->setRangeUpper(20);
    ui->widget->yAxis->setRangeUpper(100);
}


void MainWindow::Point_temp(double datay) //温度曲线绘制
{

    if(size_temp == 20)                  //20个字符之后将容器清空，容器存储太多会卡
    {
        size_temp = 0;
        x_temp.clear();
        y_temp.clear();
        ui->widget->graph(1)->data().data()->clear();
        ui->widget->replot();
    }
    x_temp.append(size_temp);            //将获取到的时间进行格式整理并转换为double类型
    y_temp.append(datay);
    graph2->addData(x_temp ,y_temp);      //添加绘图的线
    ui->widget->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectPlottables);
    ui->widget->replot();
    size_temp++;
}

void MainWindow::Point_humi(double datay) //绘制湿度曲线
{

    if(size_humi == 20)                  //20个字符之后将容器清空，容器存储太多会卡
    {
        size_humi = 0;
        x_humi.clear();
        y_humi.clear();
        ui->widget->graph(2)->data().data()->clear();
        ui->widget->replot();
    }
    x_humi.append(size_humi);            //将获取到的时间进行格式整理并转换为double类型
    y_humi.append(datay);
    graph3->addData(x_humi ,y_humi);      //添加绘图的线
    ui->widget->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectPlottables);
    ui->widget->replot();
    size_humi++;
}

void MainWindow::Point_Light(double datay)    //绘制光照曲线
{

    if(size_Light == 20)                  //20个字符之后将容器清空，容器存储太多会卡
    {
        size_Light = 0;
        x_Light.clear();
        y_Light.clear();
        ui->widget->graph(0)->data().data()->clear();
        ui->widget->replot();
    }
    x_Light.append(size_Light);            //将获取到的时间进行格式整理并转换为double类型
    y_Light.append(datay);
    graph1->addData(x_Light ,y_Light);      //添加绘图的线
    ui->widget->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectPlottables);
    ui->widget->replot();
    size_Light++;
}

void MainWindow::Point_Weight(double datay)
{

    if(size_Weight == 20)                  //20个字符之后将容器清空，容器存储太多会卡
    {
        size_Weight = 0;
        x_Weight.clear();
        y_Weight.clear();
        ui->widget->graph(3)->data().data()->clear();
        ui->widget->replot();
    }
    x_Weight.append(size_Weight);            //将获取到的时间进行格式整理并转换为double类型
    y_Weight.append(datay);
    graph4->addData(x_Weight ,y_Weight);      //添加绘图的线
    ui->widget->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectPlottables);
    ui->widget->replot();
    size_Weight++;
}

void MainWindow::Point_Water(double datay)
{

    if(size_Water == 20)                  //20个字符之后将容器清空，容器存储太多会卡
    {
        size_Water = 0;
        x_Water.clear();
        y_Water.clear();
        ui->widget->graph(4)->data().data()->clear();
        ui->widget->replot();
    }
    x_Water.append(size_Water);            //将获取到的时间进行格式整理并转换为double类型
    y_Water.append(datay);
    graph5->addData(x_Water ,y_Water);      //添加绘图的线
    ui->widget->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectPlottables);
    ui->widget->replot();
     size_Water++;
}

void MainWindow::on_pushButton_4_clicked()
{
    if(ui->pushButton_4->text() == "手动控制")
    {
        ui->pushButton_2->setEnabled(true);
        ui->pushButton_3->setEnabled(true);
        ui->pushButton_4->setText("自动控制");
    }
    else if(ui->pushButton_4->text() == "自动控制")
    {
        ui->pushButton_2->setEnabled(false);
        ui->pushButton_3->setEnabled(false);
        ui->pushButton_4->setText("手动控制");
    }
}

void MainWindow::on_pushButton_2_clicked()      //风扇开关
{
    if(ui->pushButton_2->text() == "开启状态")
    {
        QString str = "cmd=2&uid="+pass+"&topic=Open1&msg=1\r\n";
        tcpSocket->write(str.toUtf8());
    }
    else
    {
        QString str = "cmd=2&uid="+pass+"&topic=Open1&msg=0\r\n";
        tcpSocket->write(str.toUtf8());
    }
}

void MainWindow::on_pushButton_3_clicked()
{
    if(ui->pushButton_3->text() == "开启状态")
    {
        QString str = "cmd=2&uid="+pass+"&topic=Open2&msg=1\r\n";
        tcpSocket->write(str.toUtf8());
    }
    else
    {
        QString str = "cmd=2&uid="+pass+"&topic=Open2&msg=0\r\n";
        tcpSocket->write(str.toUtf8());
    }
}
